package com.ruoyi.web.controller.travel;

import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TravelCustomer;
import com.ruoyi.system.service.ITravelCustomerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户信息Controller
 */
@RestController
@RequestMapping("/travel/customer")
public class TravelCustomerController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(TravelCustomerController.class);

    @Autowired
    private ITravelCustomerService travelCustomerService;

    /**
     * 查询客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(TravelCustomer travelCustomer) {
        startPage();
        List<TravelCustomer> list = travelCustomerService.selectTravelCustomerList(travelCustomer);
        return getDataTable(list);
    }

    /**
     * 导出客户信息列表
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:export')")
    @Log(title = "客户信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TravelCustomer travelCustomer) {
        List<TravelCustomer> list = travelCustomerService.selectTravelCustomerList(travelCustomer);
        ExcelUtil<TravelCustomer> util = new ExcelUtil<TravelCustomer>(TravelCustomer.class);
        return util.exportExcel(list, "客户信息数据");
    }

    /**
     * 获取客户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:query')")
    @GetMapping(value = "/{customerId}")
    public AjaxResult getInfo(@PathVariable("customerId") Long customerId) {
        return success(travelCustomerService.selectTravelCustomerById(customerId));
    }

    /**
     * 新增客户信息
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:add')")
    @Log(title = "客户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TravelCustomer travelCustomer) {
        return toAjax(travelCustomerService.insertTravelCustomer(travelCustomer));
    }

    /**
     * 修改客户信息
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:edit')")
    @Log(title = "客户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TravelCustomer travelCustomer) {
        return toAjax(travelCustomerService.updateTravelCustomer(travelCustomer));
    }

    /**
     * 删除客户信息
     */
    @PreAuthorize("@ss.hasPermi('travel:customer:remove')")
    @Log(title = "客户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{customerIds}")
    public AjaxResult remove(@PathVariable Long[] customerIds) {
        return toAjax(travelCustomerService.deleteTravelCustomerByIds(customerIds));
    }

    /**
     * OCR识别身份证
     */
    @PostMapping("/ocr/idcard")
    public AjaxResult ocrIdCard(@RequestBody String imageBase64) {
        if (StringUtils.isEmpty(imageBase64)) {
            return error("图片数据不能为空");
        }
        try {
            Object result = travelCustomerService.ocrIdCard(imageBase64);
            if (result instanceof JSONObject) {
                JSONObject jsonResult = (JSONObject) result;
                if (jsonResult.has("error_code")) {
                    // 支持 error_code 为字符串或整数
                    Object errorCode = jsonResult.get("error_code");
                    boolean hasError = false;
                    
                    if (errorCode instanceof Integer) {
                        hasError = ((Integer) errorCode) != 0;
                    } else if (errorCode instanceof String) {
                        hasError = !("0".equals(errorCode) || "0.0".equals(errorCode));
                    } else {
                        log.warn("未知的 error_code 类型: " + errorCode.getClass().getName());
                    }
                    
                    if (hasError) {
                        return error("OCR识别失败：" + jsonResult.getString("error_msg"));
                    }
                }
            }
            return success(result);
        } catch (Exception e) {
            log.error("OCR识别失败", e);
            return error("OCR识别失败：" + e.getMessage());
        }
    }

    /**
     * OCR识别护照
     */
    @PostMapping("/ocr/passport")
    public AjaxResult ocrPassport(@RequestBody String imageBase64) {
        if (StringUtils.isEmpty(imageBase64)) {
            return error("图片数据不能为空");
        }
        try {
            Object result = travelCustomerService.ocrPassport(imageBase64);
            if (result instanceof JSONObject) {
                JSONObject jsonResult = (JSONObject) result;
                if (jsonResult.has("error_code")) {
                    // 支持 error_code 为字符串或整数
                    Object errorCode = jsonResult.get("error_code");
                    boolean hasError = false;
                    
                    if (errorCode instanceof Integer) {
                        hasError = ((Integer) errorCode) != 0;
                    } else if (errorCode instanceof String) {
                        hasError = !("0".equals(errorCode) || "0.0".equals(errorCode));
                    } else {
                        log.warn("未知的 error_code 类型: " + errorCode.getClass().getName());
                    }
                    
                    if (hasError) {
                        return error("OCR识别失败：" + jsonResult.getString("error_msg"));
                    }
                }
            }
            return success(result);
        } catch (Exception e) {
            log.error("OCR识别失败", e);
            return error("OCR识别失败：" + e.getMessage());
        }
    }
} 